
import sys
import csv

index_buffer = {}
raw_vertex_buffer = {}
final_vertex_buffer = []
semantics = []
comand_arg_nums = len(sys.argv)

def ReadCSVFile(fileName, content):    
    if content is None: return
    if type(content) is not dict: return
    content.clear()

    if fileName is '': return
    with open(fileName, mode = 'r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        row_count = 0
        for row in csv_reader:
            if row_count == 0:
                for k in list(row.keys()):
                    content[k] = []
            for k,v in row.items():
                content[k].append(v)
            row_count += 1
    pass

def GetADictRow(i, vtx_num):
    if i < 0 or i >= vtx_num: return
    if raw_vertex_buffer is None: return
    tmp_row = []
    for k in semantics:
       tmp_row.append(raw_vertex_buffer[k][i]) 
    return tmp_row

def WriteCSVFile():
    if comand_arg_nums < 3: return
    with open(sys.argv[3], mode = 'w', newline='') as csv_file:
        csv_writer = csv.writer(csv_file, delimiter=',')
        csv_writer.writerows(final_vertex_buffer)
    pass

# The first argument is the vertex buffer file
def ReadRawVertexBuffer():
    if comand_arg_nums < 1: return
    global raw_vertex_buffer
    global semantics
    ReadCSVFile(sys.argv[1], raw_vertex_buffer)
    semantics = list(raw_vertex_buffer.keys())
    # print(raw_vertex_buffer[' IDX'][0:6])
    pass

def ReadIndexBuffer():
    if comand_arg_nums < 2: return
    global index_buffer
    ReadCSVFile(sys.argv[2], index_buffer)
    # print(index_buffer[' x'][0:6])
    pass

def ConstructFinalBuffer():
    if index_buffer is None or raw_vertex_buffer is None: return

    global final_vertex_buffer
    final_vertex_buffer.clear()
    index_keys = list(index_buffer.keys())
    idx_num = len(index_buffer[index_keys[0]])
    final_vertex_buffer.append(semantics)
    for i in range(idx_num):
        for j in range(1, 4):
            final_vertex_buffer.append(GetADictRow(int(index_buffer[index_keys[j]][i]), idx_num))
    pass


ReadRawVertexBuffer()
ReadIndexBuffer()
ConstructFinalBuffer()
WriteCSVFile()